import {Buffer} from "buffer";
import {Date_time_s} from "./Date_time_s";
import {TI} from "./TI";
import {MS} from "./MS";
import {AxdrType} from "../asn1.axdr/AxdrType";
import {ReverseByteArrayInputStream} from "../ReverseByteArrayInputStream";
import {ReverseByteArrayOutputStream} from "../ReverseByteArrayOutputStream";


export class Selector6 implements AxdrType{


    dataCode : Buffer | null = null;
    dtss : Date_time_s | null = null;
    dtse : Date_time_s | null = null;
    inter : TI | null = null;
    ms : MS | null = null;

    constructor() {
    }

    set_dataCode(dataCode : Buffer){
        this.dataCode = dataCode;
    }

    set_all(dtss : Date_time_s, dtse : Date_time_s, inter : TI, ms : MS){
        this.dtss = dtss;
        this.dtse = dtse;
        this.inter = inter;
        this.ms = ms;
    }

    decode(input: ReverseByteArrayInputStream): number {
        let codeLength = 0;

        this.dtss = new Date_time_s();
        codeLength += this.dtss.decode(input);

        this.dtse = new Date_time_s();
        codeLength += this.dtse.decode(input);

        this.inter = new TI();
        codeLength += this.inter.decode(input);

        this.ms = new MS();
        codeLength += this.ms.decode(input);

        return codeLength;
    }

    encode(output: ReverseByteArrayOutputStream): number {
        let codeLength;

        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (let i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if(this.dtss != null && this.dtse != null && this.inter != null && this.ms != null){
                codeLength = 0;
                codeLength += this.ms.encode(output);

                codeLength += this.inter.encode(output);

                codeLength += this.dtse.encode(output);

                codeLength += this.dtss.encode(output);

            }else{
                throw new Error("dtss or dtse or ms or inter is null");
            }
        }

        return codeLength;
    }

    encodeAndSave(encodingSizeGuess: number) {
        let revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    toString(): string {
        if (this.dtss != null && this.dtse != null && this.ms != null && this.inter != null) {
            return "sequence: {"+ "dtss: " + this.dtss + ", dtse: " + this.dtse + ", inter: " + this.inter + ", ms: " + this.ms  + "}";
        } else {
            return "dtss or dtse or ms or inter is null";
        }
    }

}
